package cn.bincker.mybatis.encrypt.converter.utils;

import cn.bincker.mybatis.encrypt.exception.InvalidDataException;

import java.nio.ByteBuffer;
import java.time.Instant;

public class BinaryUtils {
    private static final int INSTANT_BYTES = Long.BYTES + Integer.BYTES;
    private static final char[] HEX_DIST = "0123456789abcdef".toCharArray();
    public static String binary2Hex(byte[] data){
        var result = new StringBuilder();
        for (byte datum : data) {
            result.append(HEX_DIST[(datum >> 4) & 0x0f]);
            result.append(HEX_DIST[datum & 0x0f]);
        }
        return result.toString();
    }

    public static Instant binary2instant(byte[] data){
        if (data.length < INSTANT_BYTES) throw new InvalidDataException("instant need " + INSTANT_BYTES + " bytes but got " + data.length);
        var byteBuffer = ByteBuffer.wrap(data);
        return Instant.ofEpochSecond(byteBuffer.getLong(), byteBuffer.getInt());
    }

    public static byte[] instant2binary(Instant instant){
        byte[] data = new byte[INSTANT_BYTES];
        ByteBuffer.wrap(data).putLong(instant.getEpochSecond()).putInt(instant.getNano());
        return data;
    }
}
